package com.csaba.swing.model;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;

import com.csaba.connector.BankServiceFactory;
import com.csaba.connector.ServiceException;
import com.csaba.connector.model.Account;
import com.csaba.connector.model.Session;
import com.csaba.connector.service.AccountService;
import com.csaba.swing.MainWindow;
import com.csaba.swing.action.ServiceRunner;
import com.csaba.util.LoggerHelper;

public class AccountCache extends SessionCache<Account>
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	private static AccountCache instance;

	public static AccountCache getInstace()
	{
		if ( instance == null )
		{
			instance = new AccountCache();
		}
		return instance;
	}

	@Override
	protected Account[] load( final Session session )
	{
		try
		{
			final AccountService service = BankServiceFactory.getBankService(session.getBank(), AccountService.class);
			( new ServiceRunner(session, service, "Getting account list for customer " + session.getCustomer()) )
					.execute();
			final Account[] accounts = service.getAccounts();
			return accounts;
		}
		catch ( final ServiceException ex )
		{
			logger.log(Level.SEVERE, "Error loading accounts.", ex);
			JOptionPane.showMessageDialog(MainWindow.getFrame(), "Error during loading accounts for customer "
					+ session.getCustomer().getName() + "\n" + ex.getMessage() + "\n" + ex.getNativeMessage(), "Error",
					JOptionPane.ERROR_MESSAGE);
		}
		catch ( final Exception ex )
		{
			logger.log(Level.SEVERE, "Error loading accounts.", ex);
			JOptionPane.showMessageDialog(MainWindow.getFrame(), "Fatal error during loading accounts." + "\n"
					+ ex.getMessage(), "Fatal Error", JOptionPane.ERROR_MESSAGE);
		}
		return null;
	}

}
